package com.yequan.rocketmq.order;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.UnsupportedEncodingException;

/**
 * @author yq
 * @date 2020/09/10
 */
public class OrderProducerTest {

    private ApplicationContext context;

    @Before
    public void init() {
        context = new ClassPathXmlApplicationContext("classpath:spring-orderproducer.xml");
    }

    @Test
    public void sendMessage() throws UnsupportedEncodingException, InterruptedException, RemotingException, MQClientException, MQBrokerException {
        OrderProducer producer = (OrderProducer) context.getBean("producer");
        OrderMessageQueueSelector orderMessageQueueSelector = (OrderMessageQueueSelector) context.getBean("orderMessageQueueSelector");
        String topicName = "topic_order";
        String[] statusNames = {"已创建", "已付款", "已配送", "已取消", "已完成"};
        //模拟订单消息
        for (int orderId = 1; orderId <= 10; orderId++) {
            //模拟订单的每个状态来发送消息
            for (int i = 0; i < statusNames.length; i++) {
                String messageContent = new OrderMessage()
                        .setId(orderId)
                        .setStatus(statusNames[i])
                        .setSendOrder(i)
                        .setContent("Hello orderly rocketMQ message!")
                        .toString();
                Message message = new Message(topicName, statusNames[i], orderId + "#" + statusNames[i], messageContent.getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.getProducer().send(message, orderMessageQueueSelector, orderId);
                System.out.printf("%s %n", sendResult);
            }
        }
    }

}
